package view;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import representation.RepresentationManager;

import controller.PlayerController;
import entity.EntityManager;
import entity.Player;

public class Game extends Canvas {
	
	private BufferStrategy strategy;
	private boolean gameRunning;
	EntityManager entities;
	RepresentationManager representations;
	
	
	public Game() {
		JFrame container = new JFrame("awwwwww yeah");
		this.gameRunning = true;
		
		JPanel panel = (JPanel) container.getContentPane();
		panel.setPreferredSize(new Dimension(500, 500));
		panel.setLayout(null);
		
		setBounds(0,0,500,500);
		panel.add(this);
		
		setIgnoreRepaint(true);
		
		container.pack();
		container.setResizable(false);
		container.setVisible(true);
		
		container.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		
		representations = new RepresentationManager();
		entities = new EntityManager(representations);
		
		Player p = new Player(new PlayerController());
		addKeyListener((KeyListener) p.getController());
		entities.addEntity(p);
		
		requestFocus();
		
		createBufferStrategy(2);
		this.strategy = getBufferStrategy();
	}
	
	public void startGame() {
		long lastLoopTime = System.currentTimeMillis();
		
		while (gameRunning) {
			long delta = System.currentTimeMillis() - lastLoopTime;
			lastLoopTime = System.currentTimeMillis();
			
			Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
			g.setBackground(Color.BLACK);
			g.clearRect(0, 0, 500, 500);
			
			this.entities.update();
			this.representations.draw(g);
			
			g.dispose();
			strategy.show();
			
			try { Thread.sleep(30); } catch (Exception e) {}
		}
	}

	public static void main(String[] args) {
		new Game().startGame();
	}
	
}